package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 时间表，异步写入 业务层
 */
@Service
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async //异步执⾏，原理：底层开⼀个线程去执⾏该⽅法
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId, Long date) {
        // 查询好友列表
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Users> usersList = this.mongoTemplate.find(query, Users.class);

        try {
            if (CollUtil.isEmpty(usersList)) {
                // 返回成功
                return CompletableFuture.completedFuture("ok");
            }

            // 为每个好友添加时间线表
            TimeLine timeLine = new TimeLine();
            timeLine.setId(ObjectId.get()); // 主键id
            timeLine.setUserId(userId); // 好友id
            timeLine.setPublishId(publishId); // 发布id
            timeLine.setDate(date); // 发布时间
            for (Users users : usersList) {
                this.mongoTemplate.save(timeLine, "quanzi_time_line_" + users.getFriendId());
            }
        } catch (Exception e) {
            //TODO 事务回滚问题
            return CompletableFuture.completedFuture("error");
        }
        return CompletableFuture.completedFuture("ok");
    }

}
